package com.fz.us.oa.web.controller.mp;

import com.fz.us.admin.base.utils.Identities;
import com.fz.us.admin.base.utils.LogUtil;
import com.fz.us.admin.base.utils.StringUtils;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import fz.me.chanjar.weixin.common.api.WxConsts;
import fz.me.chanjar.weixin.common.exception.WxErrorException;
import fz.me.chanjar.weixin.mp.api.WxMpService;
import fz.me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import fz.me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 控制器 - 登录
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-07-29 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/mp")
public class WxLoginController extends BaseController {

    private static final long serialVersionUID = -7233017017119091789L;

    private static final String webLoginResult = "/mp/login";
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(@CurrentUser User user, Model model, HttpServletResponse response, HttpServletRequest request, String openId, String code) {
        getData(user,model, response, request, openId, code);
        return webLoginResult;
    }


    @RequestMapping(value = "adminlogin", method = RequestMethod.GET)
    public String adminlogin(@CurrentUser User user,Model model, HttpServletResponse response, HttpServletRequest request, String openId, String code) {
        getData(user,model, response, request, openId, code);
        return "/mp/adminlogin";
    }

    public void getData(User user, Model model, HttpServletResponse response, HttpServletRequest request, String openId, String code){
        String error = null;
        String nickname = null;
        String headimgurl = null;
        String redirectUrl = null;
        try {
            if(StringUtils.isNotEmpty(openId)){
                error =  request.getParameter("state");
                LogUtil.info("{state}" + error);
                WxMpUser wxMpUser = null;
                wxMpUser = wxMpService.userInfo(openId, WxConsts.CN);
                nickname = wxMpUser.getNickname();
                headimgurl = wxMpUser.getHeadImgUrl();
            }else if(StringUtils.isNotEmpty(code)){
                LogUtil.info("{code}" + code);
                error = request.getParameter("state");
                LogUtil.info("{state}" + error);
                WxMpOAuth2AccessToken oAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
                LogUtil.info("oAuth2AccessToken" + oAuth2AccessToken.toString());
                WxMpUser wxMpUser = wxMpService.userInfo(oAuth2AccessToken.getOpenId(), WxConsts.CN);
                //该接口需要弹出式授权控制，此处不使用！！oauth2getUserInfo(oAuth2AccessToken,WxConsts.CN);
                openId = wxMpUser.getOpenId();
                nickname = wxMpUser.getNickname();
                headimgurl = wxMpUser.getHeadImgUrl();
            }else{
                error = request.getParameter("error");

                try {
                    error = UriUtils.encodeQueryParam(error, "utf8");
                } catch (UnsupportedEncodingException e) {
                    error = "";
                }

                redirectUrl = wxMpService.oauth2buildAuthorizationUrl("snsapi_base", "");
                LogUtil.info("{redirectUrl}"+redirectUrl);

                try {
                    response.sendRedirect(redirectUrl);
                } catch (IOException e) {

                }
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            error = "【账号异常，请稍后再试】";
        } finally {

        }
        model.addAttribute("error", error);
        model.addAttribute("nickname", nickname);
        model.addAttribute("headimgurl", headimgurl);
        model.addAttribute("redirectUrl", redirectUrl);
        model.addAttribute("openId", openId);
        model.addAttribute("user", user);
    }


    /**
     * 如果没有权限则直接跳转到登录界面
     * */
    @RequestMapping(value = "account/resetMp", method = RequestMethod.GET)
    public String resetMp(@CurrentUser User user,Model model) throws Exception {
       String openId = userService.openId(user);
       int ifWxUsers = userService.isWxUsers(openId)==true?1:0;
       String nickname = null;
       String headimgurl = null;
        if(StringUtils.isNotEmpty(openId)){
            try {
                WxMpUser mpUser = wxMpService.userInfo(openId, WxConsts.CN);
                nickname = mpUser.getNickname();
                headimgurl = mpUser.getHeadImgUrl();
            }catch (WxErrorException e){

            }finally {

            }
        }
        if(StringUtils.isEmpty(nickname)){
            //跳转到login重新绑定
            nickname = "账号绑定异常，如有问题请重置账号。";
            headimgurl = "../resource/core/img/male.png";
            model.addAttribute("nickname",  nickname);
            model.addAttribute(" headimgurl",   headimgurl);
            return "/mp/login";
        }
        model.addAttribute("ifWxUsers",  ifWxUsers);
        model.addAttribute("nickname",  nickname);
        model.addAttribute("headimgurl",   headimgurl);
        model.addAttribute("openId", openId);
        model.addAttribute("user", user);
        return "/mp/account_reset";
    }
}
